import os
from flask import Flask, request, redirect, render_template, url_for, flash
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/uploads'
ALLOWED_EXTENSIONS = {'html'}
CLASS_SECRET_CODE = "szpt2025cloudclass2"  # 班级口令
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024  # 限制2MB上传
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = 'a_strong_secret_key'

# 验证文件类型
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 上传页面
@app.route('/')
def upload_form():
    return render_template('upload.html')

# 简历墙页面（核心修复：生成Nginx绝对路径）
@app.route('/wall')
def resume_wall():
    try:
        all_files = os.listdir(app.config['UPLOAD_FOLDER'])
        html_files = sorted([f for f in all_files if f.endswith('.html')])
        # 固定Nginx地址（服务器IP+学号端口8068）
        nginx_base_url = "http://192.168.200.20:8068"
        return render_template('wall.html', resumes=html_files, nginx_url=nginx_base_url)
    except FileNotFoundError:
        return render_template('wall.html', resumes=[], nginx_url="")

# 处理上传逻辑
@app.route('/upload', methods=['POST'])
def upload_file():
    if request.form.get('secret_code') != CLASS_SECRET_CODE:
        flash('班级口令错误！')
        return redirect(url_for('upload_form'))
    
    if 'file' not in request.files or not request.form.get('student_name'):
        flash('姓名和文件不能为空')
        return redirect(request.url)
    
    file = request.files['file']
    student_name = request.form.get('student_name')

    if file and allowed_file(file.filename):
        final_filename = f"{secure_filename(student_name)}.html"
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], final_filename)
        
        if os.path.exists(file_path):
            flash(f"错误：文件 '{final_filename}' 已存在！")
            return redirect(url_for('upload_form'))

        file.save(file_path)
        # 上传成功后跳转至简历墙
        return f"上传成功！<a href='/wall' target='_blank'>点击查看简历墙</a>。<br><a href='/'>返回上传</a>"

    flash('文件类型不允许（仅支持HTML）')
    return redirect(request.url)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)  # 允许外部访问